<?php
/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */ 
class Game_Form_Admin_Game_Create extends Engine_Form
{

  public function isValid($data)
  {
    /*
    echo "<pre>";
    print_r($data);
    echo "</pre>";
    */
    $valid = parent::isValid($data);
    $this->setHeaderFields();
    return $valid;
  }
  
  public function init()
  {
    $user = Engine_Api::_()->game()->getDefaultOwner();    
    $user_level = $user->level_id;    
    
    $this->setTitle('Add New Game')
      ->setDescription('Please fill out the form below to add new game.')
      ->setAttrib('name', 'games_create');

    $translate = Zend_Registry::get('Zend_Translate');
      
    $categories_prepared = Engine_Api::_()->getItemTable('game_category')->getMultiOptionsAssoc();
    $categories_prepared = array(""=>"") + $categories_prepared;
    
    // category field
    $this->addElement('Select', 'category_id', array(
      'label' => 'Category',
      'multiOptions' => $categories_prepared,
      'allowEmpty' => false,
      'required' => true,
      'validators' => array(
        array('NotEmpty', true),
      ),
      'filters' => array(
       'Int'
      ),
    ));      
   
    $this->addElement('Text', 'title', array(
      'label' => 'Game Title',
      'allowEmpty' => false,
      'required' => true,
      'filters' => array(
        'StringTrim',
      )
    ));
    $this->title->getDecorator("Description")->setOption("placement", "prepend");       

    
    // Description
    $this->addElement('Textarea', 'description', array(
      'label' => 'Description',
      'description' => 'Describe this game with your own words.',
      'allowEmpty' => false,
      'required' => true,
      'filters' => array(
        'StripTags',
      ),     
    ));
    $this->description->getDecorator("Description")->setOption("placement", "prepend");        
    
 
    
    $this->addElement('Text', 'keywords',array(
      'label'=>'Tags (Keywords)',
      'autocomplete' => 'off',
      'description' => 'Separate tags with commas.',
      'filters' => array(
        new Engine_Filter_Censor(),
      ),
    ));
    $this->keywords->getDecorator("Description")->setOption("placement", "append");    
           

    $this->addElement('Heading', 'head_general', array(
      'label' => $translate->translate('Game Information')
    ));

    $this->addElement('File', 'swf_file', array(
      'label' => 'Game File',
      'description' => 'Select a game file from your local computer (swf). Note: if you do not want to upload game file to your server, you can fill out "Game File URL" field right below.'
    ));
    $this->swf_file->addValidator('Extension', false, 'swf');   
    
    $this->addElement('Text', 'swf_url', array(
      'label' => '(or) Game File URL',
      'description' => 'Enter complete URL to the game swf file (ie hot-link to it, starting with http:// and end with swf extension) if you do not upload game file above.',
      'filters' => array(
        'StringTrim',
      ),
      'validators' => array(
        new Engine_Validate_Callback(array($this, 'validateSwfUrl')),
      ),  
    ));
    $this->swf_url->getDecorator("Description")->setOption("placement", "prepend"); 
    
    $this->addElement('Text', 'width', array(
      'label' => 'Game Width',
      'allowEmpty' => false,
      'required' => true,
      'validators' => array(
        'Int',
        new Zend_Validate_GreaterThan(0),
      ),
      'class' => 'short',
    ));
    $this->width->getDecorator("Description")->setOption("placement", "append");
    
    $this->addElement('Text', 'height', array(
      'label' => 'Game Height',
      'allowEmpty' => false,
      'required' => true,
      'validators' => array(
        'Int',
        new Zend_Validate_GreaterThan(0),
      ),
      'class' => 'short',
    ));
    $this->height->getDecorator("Description")->setOption("placement", "append");

    $this->addElement('File', 'photo', array(
      'label' => 'Photo'
    ));
    $this->photo->addValidator('Extension', false, 'jpg,png,gif,jpeg');      
    
    $this->addElement('Text', 'thumbnail_url', array(
      'label' => '(or) Photo URL',
    	'description' => 'Enter complete URL to game photo (ie hot-link to it, starting with http://) if you do not upload any photo above. Recommended dimension is 100x100.',
      'filters' => array(
        'StringTrim',
      )
    ));
    $this->thumbnail_url->getDecorator("Description")->setOption("placement", "prepend"); 
    
    $this->addElement('Textarea', 'instructions', array(
      'label' => 'Game Instructions',
      'description' => 'Write a short details on how to play this game.',   
      'filters' => array(
        'StripTags',
      ),     
    ));
    $this->instructions->getDecorator("Description")->setOption("placement", "prepend");   
    
    $this->addElement('Textarea', 'controls', array(
      'label' => 'Game Controls',
      'description' => 'Provide info for game control key press.',
      'filters' => array(
        'StripTags',
      ),     
    ));
    $this->controls->getDecorator("Description")->setOption("placement", "prepend");  
    
    $this->addElement('Textarea', 'embed_code', array(
      'label' => 'Custom Embed Code',
      'description' => 'This optional custom embed code will be shown in the flash game output instead of using built-in embed code. Available placeholders: {{width}} {{height}} {{swf}}',    
      'filters' => array(
        'StringTrim',
      )    
    ));
      
    
    $this->addElement('Select', 'content_rating', array(
    	'label' => 'Content Rating',
    	'multiOptions' => Game_Form_Helper::getContentRatings()
    ));    
    
    $this->addElement('Radio', 'leaderboard_enabled', array(
    	'label' => 'Mochi Leaderboard Supported?',
    	'description' => "If this game support Mochi leaderboard API, please check YES, otherwise, please check NO.",
    	'multiOptions' => Game_Form_Helper::getYesNo(),
    	'value' => 0
    )); 
    
    /*
    $this->addElement('Heading', 'head_distributor', array(
      'label' => $translate->translate('Distributor Information')
    ));
    */
    
    $this->addElement('Select', 'distributor_type', array(
    	'label' => 'Distributor Type',
    	'multiOptions' => Game_Form_Helper::getDistributorTypes()
    )); 
    
    $this->addElement('Text', 'distributor_ref_id', array(
      'label' => 'Distributor Reference ID',
      'description' => 'Optional unique id that reference the game on distributor catalog.',
    ));
    $this->distributor_ref_id->getDecorator("Description")->setOption("placement", "prepend"); 
    
    $this->addElement('Text', 'distributor_ref_slug', array(
      'label' => 'Distributor Reference Slug',
      'description' => 'Optional unique slug that reference the game on distributor catalog. This slug is required to display Mochie supported leaderboard widget.',
    ));
    $this->distributor_ref_slug->getDecorator("Description")->setOption("placement", "prepend"); 
    
    
    $this->addElement('Text', 'developer_name', array(
      'label' => 'Developer Name',
    	'description' => 'To give credit to this game, please enter its developer name',
    ));
    
    // Add subforms
    if( !$this->_item ) {
      $customFields = new Game_Form_Custom_Fields();
    } else {
      $customFields = new Game_Form_Custom_Fields(array(
        'item' => $this->getItem()
      ));
    }
    if( get_class($this) == 'Game_Form_Admin_Game_Create' ) {
      $customFields->setIsCreation(true);
    }

    $this->addSubForms(array(
      'fields' => $customFields
    ));
        
    $this->addElement('Heading', 'head_privacy', array(
      'label' => $translate->translate('Privacy Details')
    ));    
    
    // View
    $availableLabels = array(
      'everyone'              => 'Everyone',
      'registered'            => 'Registered Members',
      'owner_network'         => 'Friends and Networks',
      'owner_member_member'   => 'Friends of Friends',
      'owner_member'          => 'Friends Only',
      'owner'                 => 'Just Me'
    );
    
    
    $options = (array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('game', $user, 'auth_view');
    $options = array_intersect_key($availableLabels, array_flip($options));

    $this->addElement('Select', 'auth_view', array(
      'label' => 'View Privacy',
      'description' => 'Who may see this game?',
      'multiOptions' => $options,
      'value' => 'everyone',
    ));
    $this->auth_view->getDecorator('Description')->setOption('placement', 'prepend');

    $options =(array) Engine_Api::_()->authorization()->getAdapter('levels')->getAllowed('game', $user, 'auth_comment');
    $options = array_intersect_key($availableLabels, array_flip($options));

    // Comment
    $this->addElement('Select', 'auth_comment', array(
      'label' => 'Comment Privacy',
      'description' => 'Who may post comments on this game?',
      'multiOptions' => $options,
      'value' => 'registered',
    ));
    $this->auth_comment->getDecorator('Description')->setOption('placement', 'prepend');

    
    $this->addElement('Select', 'status', array(
    	'label' => 'Status',
    	'multiOptions' => Game_Form_Helper::getStatuses()
    ));
        
    
    $this->addElement('Checkbox', 'featured', array(
      'label' => 'Mark this game as featured',
      'value' => 0
    ));

    $this->addElement('Checkbox', 'sponsored', array(
      'label' => 'Mark this game as sponsored',
      'value' => 0
    ));    
    
    $this->addElement('Checkbox', 'search', array(
      'label' => 'Show this game in browse and search results',
      'value' => 1
    ));
    
    // Buttons
    $this->addElement('Button', 'submit', array(
      'label' => 'Add Game',
      'type' => 'submit',
      'ignore' => true
    ));

    $this->setHeaderFields();
  }

  /**
   * hack to fix:
   * 1) display styling
   * 2) header name (label/value) disappear when submitted form with error
   */
  public function setHeaderFields()
  {
    $header_fields = array('head_general', 'head_privacy');
    foreach ($header_fields as $header_field) {
      
      $label = Zend_Registry::get('Zend_Translate')->_($this->$header_field->getLabel());
      $this->$header_field->setValue($label);
      $this->$header_field->setIgnore(true);
      $this->$header_field->removeDecorator('Label')
          ->removeDecorator('HtmlTag')
          ->getDecorator('HtmlTag2')->setOption('class', 'form-wrapper-heading');
    }
  }  
  
  public function validateSwfUrl($value)
  {
    if (!Zend_Uri::check($value)) {
      $this->swf_url->getValidator('Engine_Validate_Callback')->setMessage('Invalid SWF URL, make sure it is a well-formed URI, starting with http://');
      return false;
    }

    return true;
  }   
    
  public function validatePhotoUrl($value)
  {
    if (!Zend_Uri::check($value)) {
      $this->thumbnail_url->getValidator('Engine_Validate_Callback')->setMessage('Invalid Photo URL, make sure it is a well-formed URI, starting with http://');
      return false;
    }

    return true;
  } 
}